package com.example.utils.mybatis;


import com.google.common.base.CaseFormat;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 扩展 Mybatis 注解，作用于 update 更新操作上
 */
public class SimpleUpdateLanguageDriver extends XMLLanguageDriver implements LanguageDriver {

    @Override
    public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {

        // 正则匹配
        Pattern inPattern = Pattern.compile("\\(#\\{(\\w+)\\}\\)");
        Matcher matcher = inPattern.matcher(script);
        if (matcher.find()) {
            StringBuffer buffer = new StringBuffer();
            buffer.append("<set>");

            // 驼峰式命名
            for (Field field : parameterType.getDeclaredFields()) {
                // 排除被 Invisble 修饰的变量
                if (!field.isAnnotationPresent(Invisible.class)){
                    String str = "<if test=\"__field != null\">__column=#{__field},</if>";
                    buffer.append(str.replaceAll("__field", field.getName()).replaceAll("__column", CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field.getName())));
                }
            }

            buffer.deleteCharAt(buffer.lastIndexOf(","));
            buffer.append("</set>");

            script = matcher.replaceAll(buffer.toString());
            script = "<script>" + script + "</script>";

            System.out.println("SimpleUpdateLanguageDriver - 生成的SQL：" + script);
        }

        return super.createSqlSource(configuration, script, parameterType);
    }
}
